package com.jstyle.nordic_otas.nordic_otas_plugin;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by Administrator on 2018/9/15.
 */

public class ZipUtils {

    public static final String fromPath1 = Environment.getExternalStorageDirectory().getPath() + "/com.jstyle.app";

    public static String getFromPath(Context context){
        if(Build.VERSION.SDK_INT >= 29){
            return context.getExternalCacheDir().getPath() + "/update/";
        }else{
            return fromPath1 + "/update/";
        }
    }

    private static final String TAG = "ZipUtils";
    /**
     * 含子目录的文件压缩
     *
     * @throws Exception
     */
    // 第一个参数就是需要解压的文件，第二个就是解压的目录
    public static boolean upZipFile(String zipFile, String folderPath) {
        ZipFile zfile = null;
        try {
            // 转码为GBK格式，支持中文
            zfile = new ZipFile(zipFile);
        } catch (IOException e) { return false; }
        Enumeration zList = zfile.entries();
        ZipEntry ze = null;
        byte[] buf = new byte[1024];
        File folderFile=new File(folderPath);
        if(!folderFile.exists()){
            folderFile.mkdirs();
        }
        while (zList.hasMoreElements()) {
            ze = (ZipEntry) zList.nextElement();
            // 列举的压缩文件里面的各个文件，判断是否为目录
            if (ze.isDirectory()) {
                String dirstr = folderPath + ze.getName();
                Log.i(TAG, "dirstr=" + dirstr);
                dirstr.trim();
                File f = new File(dirstr);
                f.mkdir();
                continue;
            }
            OutputStream os = null;
            FileOutputStream fos = null;
            // ze.getName()会返回 script/start.script这样的，是为了返回实体的File
            File realFile = getRealFileName(folderPath, ze.getName());
            try {
                fos = new FileOutputStream(realFile);
            } catch (FileNotFoundException e) { return false; }
            os = new BufferedOutputStream(fos);
            InputStream is = null;
            try {
                is = new BufferedInputStream(zfile.getInputStream(ze));
            } catch (IOException e) { return false; }
            int readLen = 0;
            // 进行一些内容复制操作
            try {
                while ((readLen = is.read(buf, 0, 1024)) != -1) {
                    os.write(buf, 0, readLen);
                }
            } catch (IOException e) { return false; }
            try {
                is.close();
                os.close();
            } catch (IOException e) { return false; }
        }
        try {
            zfile.close();
        } catch (IOException e) { return false; }
        return true;
    }

    /**
     * 给定根目录，返回一个相对路径所对应的实际文件名.
     *
     * @param baseDir
     *            指定根目录
     * @param absFileName
     *            相对路径名，来自于ZipEntry中的name
     * @return java.io.File 实际的文件
     */
    public static File getRealFileName(String baseDir, String absFileName) {
        Log.i(TAG, "baseDir=" + baseDir + "------absFileName="
                + absFileName);
        absFileName = absFileName.replace("\\", "/");
        Log.i(TAG, "absFileName=" + absFileName);
        String[] dirs = absFileName.split("/");
        Log.i(TAG, "dirs=" + dirs);
        File ret = new File(baseDir);
        String substr = null;
        if (dirs.length > 1) {
            for (int i = 0; i < dirs.length - 1; i++) {
                substr = dirs[i];
                ret = new File(ret, substr);
            }

            if (!ret.exists())
                ret.mkdirs();
            substr = dirs[dirs.length - 1];
            ret = new File(ret, substr);
            return ret;
        } else {
            ret = new File(ret, absFileName);
        }
        return ret;
    }

    public static byte[] readFile(File file) {
        // 需要读取的文件，参数是文件的路径名加文件名
        if (file.isFile()) {
            // 以字节流方法读取文件
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                // 设置一个，每次 装载信息的容器
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                // 开始读取数据
                int len = 0;// 每次读取到的数据的长度
                while ((len = fis.read(buffer)) != -1) {// len值为-1时，表示没有数据了
                    // append方法往sb对象里面添加数据
                    outputStream.write(buffer, 0, len);
                }
                // 输出字符串
                return outputStream.toByteArray();
            } catch (IOException e) { }
        } else {
            System.out.println("文件不存在！");
        }
        return null;
    }
    public static String loadFromSDFile(String path) {
        String result = null;
        try {
            File f = new File(path);
            if(!f.exists())return result;
            int length = (int) f.length();
            byte[] buff = new byte[length];
            FileInputStream fin = new FileInputStream(f);
            fin.read(buff);
            fin.close();
            result = new String(buff, StandardCharsets.UTF_8);
        } catch (Exception e) { }
        return result;
    }
    public static byte[] getMd5Byte(String md5String) {
        int length = md5String.length() / 2;
        byte[] value = new byte[length];
        for (int i = 0; i < length; i++) {
            String s = md5String.substring(i * 2, i * 2 + 2);
            value[i] = getByte(s);
        }
        return value;
    }
    private static  byte getByte(String trim) {
        if (TextUtils.isEmpty(trim)) return 0;
        return (byte) Integer.parseInt(trim, 16);
    }


    public static void copyFileFromAssets(Context context, String assetsPath) {
        File file = new File(getFromPath(context));
        try {
            if(file.exists()){
                deleteDirectory(file) ;
            }
            file.mkdirs();
            File fileMusic = new File(file ,assetsPath);
            fileMusic.createNewFile();
            AssetManager assetManager = context.getAssets();
            InputStream inputStream = assetManager.open(assetsPath);
            OutputStream outputStream = new FileOutputStream(fileMusic);
            byte[] buffer = new byte[1024];
            while (inputStream.read(buffer) > 0) {
                outputStream.write(buffer);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public static boolean needResUpdate(String zipFile) {
        ZipFile zfile = null;
        try {
            // 转码为GBK格式，支持中文
            zfile = new ZipFile(zipFile);
        } catch (IOException e) { return false; }
        Enumeration zList = zfile.entries();
        ZipEntry ze = null;
        while (zList.hasMoreElements()) {//是否需要资源文件升级
            ze = (ZipEntry) zList.nextElement();
            System.out.println("dirstr=" + ze.getName());
            String name=ze.getName();
            if("color565.bin".equals(name))return true;
            if (ze.isDirectory()) continue;

        }
        return false;
    }

    public static String copyFile(Context context, InputStream fileInputStream, String fileName) {
        String path=null;
        File file = new File(context.getFilesDir().getAbsolutePath());
        try {
            if (!file.exists()) {
                file.mkdirs();
            }
            File fileOTA = new File(file, "ota");
            if (!fileOTA.exists()) {
                fileOTA.mkdir();
            }
            File fileMusic = new File(fileOTA, fileName);
            if (fileMusic.exists()) {
                fileMusic.delete();
            }
            fileMusic.createNewFile();
            OutputStream outputStream = new FileOutputStream(fileMusic);
            byte[] buffer = new byte[1024];
            if (fileName.endsWith("zip")) {
                while (fileInputStream.read(buffer) > 0) {
                    outputStream.write(buffer);
                }
            } else {
                int byteRead;
                while ((byteRead = fileInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, byteRead);
                }
            }

            outputStream.flush();
            fileInputStream.close();
            outputStream.close();
            path = fileMusic.getAbsolutePath();
            Log.i(TAG, "copyFileFromUri: " + path + " " + fileMusic.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    public static void copyFiles(File sourceLocation, String targtLocation) throws IOException {
        if (sourceLocation.exists()) {
            FileInputStream fin = null;
            FileOutputStream fout = null;
            Log.i("debug", "source " + sourceLocation);
            Log.i("debug", "des " + targtLocation);
            try {
                fin = new FileInputStream(sourceLocation);
                new File(String.valueOf(targtLocation)).delete();
                fout = new FileOutputStream(targtLocation, false);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // Copy the bits from instream to outstream
            byte[] buf = new byte[2048];
            int len;
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fout);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fin);
            while ((len = bufferedInputStream.read(buf)) > 0) {
                bufferedOutputStream.write(buf, 0, len);
            }
            fin.close();
            bufferedOutputStream.close();
            fout.close();
            Log.e("debug", "Copy file successful.");
        } else {
            Log.v("debug", "Copy file failed. Source file missing.");
        }
    }


    // 删除文件夹
    private static void deleteDirectory(File file) {
        if (file.isFile()) {// 表示该文件不是文件夹
            file.delete();
        } else {
            // 首先得到当前的路径
            String[] childFilePaths = file.list();
            for (String childFilePath : childFilePaths) {
                File childFile = new File(file.getAbsolutePath() + "/" + childFilePath);
                deleteDirectory(childFile);
            }
            file.delete();
        }
    }

    public static byte[] checkUpdateFile(byte[] binByte, byte[] binMd5,int fileNumber,boolean LanguageUp) {
        return checkFile(binByte, binMd5, 1, fileNumber);
    }
    public static byte[] endUpdateFile(byte[] binByte, byte[] binMd5,int fileNumber) {//数据全部发送完成检查是否升级成功
        return checkFile(binByte, binMd5, 2, fileNumber);
    }
    private static byte[] checkFile(byte[] binByte, byte[] binMd5, int mode, int fileNumber) {
        int length = binByte.length;
        int crc16 = CalcCRC16(binByte, binByte.length);
        byte[] value = new byte[27];
        value[0] = (byte) 0x92;
        value[1] = (byte) mode;
        value[2] = (byte) fileNumber;
        value[3] = (byte) ((length) & 0xff);//低位在前
        value[4] = (byte) ((length >> 8) & 0xff);
        value[5] = (byte) ((length >> 16) & 0xff);
        value[6] = (byte) ((length >> 24) & 0xff);
        value[7] = (byte) ((crc16) & 0xff);
        value[8] = (byte) ((crc16 >> 8) & 0xff);
        System.arraycopy(binMd5, 0, value, 9, binMd5.length);
        int crcValue16 = CalcCRC16(value, 25);
        value[25] = (byte) ((crcValue16) & 0xff);
        value[26] = (byte) ((crcValue16 >> 8) & 0xff);
        return value;
    }

    public static int CalcCRC16(byte[] pArray, int length) {
        int wCRC = 0xFFFF;
        int CRC_Count = length;
        int i;
        int num = 0;
        while (CRC_Count > 0) {
            CRC_Count--;
            wCRC = wCRC ^ (0xFF & pArray[num++]);
            for (i = 0; i < 8; i++) {
                if ((wCRC & 0x0001) == 1) {
                    wCRC = wCRC >> 1 ^ 0xA001;
                } else {
                    wCRC = wCRC >> 1;
                }
            }
        }
        return wCRC;
    }

    public static byte[] ArrListToByteArray(List<Integer> arr){
        byte[] bytes = new byte[0];
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(arr);
            bytes = bos.toByteArray();
        }catch (Exception e){

        }
        return bytes;

    }

}
